package com.sec.etech.employeesync.confighandler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sec.etech.employeesync.entity.OrgEmployeeZSchool;
import com.sec.etech.employeesync.mapper.OrgEmployeeZSchoolMapper;
import com.sec.etech.employeesync.util.ConfigTableHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
@Slf4j
public class DegreeSchoolConfigHandler implements ConfigTableHandler<OrgEmployeeZSchool> {

    @Resource
    private OrgEmployeeZSchoolMapper schoolMapper;

    @Override
    public Long getOrCreateConfigId(String... params) {
        String name = params[0];
        OrgEmployeeZSchool school = getEntityByName(name);
        if (school == null) {
            school = new OrgEmployeeZSchool();
            school.setCode(generateNextCode());
            school.setName(name);
            school.setActive(1);
            insertEntity(school);
            log.info("新增学校配置:name={}", name);
        }
        return school.getSchoolId();
    }

    @Override
    public OrgEmployeeZSchool getEntityByName(String name) {
        return schoolMapper.selectOne(Wrappers.<OrgEmployeeZSchool>lambdaQuery()
                .eq(OrgEmployeeZSchool::getName, name));
    }

    @Override
    public String generateNextCode() {
        OrgEmployeeZSchool politics = schoolMapper.selectOne(Wrappers.<OrgEmployeeZSchool>lambdaQuery()
                .orderByDesc(OrgEmployeeZSchool::getCode)
                .last("limit 1"));

        String lastCode = Optional.ofNullable(politics)
                .map(OrgEmployeeZSchool::getCode)
                .orElse("0");

        return generateNextCode(lastCode);
    }

    @Override
    public void insertEntity(OrgEmployeeZSchool entity) {
        schoolMapper.insert(entity);
    }
}
